$(document).ready(function() {
    var num  = 0;
    let flag = true;

    // 发送消息函数
    function sendMessage() {
        const message = $('#message-input').html().trim();
        if (message) {
            flag = true;
            addMessage(message, 'user-message');
            $('#message-input').html('');

            param = "message=" + message;
            fetch("/zhipu/ai/generateStream", {
                method: 'POST',
                headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                body: param
            }).then((async result => {
                const reader = result.body.getReader();
                const textDecoder = new TextDecoder("utf-8");

                //生成唯一id
                let amId = "ai-message" + ++num;

                while(true){
                    const {done, value} = await reader.read();
                    if(done) {
                        return
                    }
                    // 此处的响应内容为 data:正文\n，也不是JSON，所以需要进行处理
                    let content = textDecoder.decode(value).substring(5);
                    content = content.substring(0, content.length-2);
                    if (content.length >= 1) {
                        let res = sanitizeString(content);
                        if(res.trim() != '') addMessage(res,amId);
                    }
                }
            }));
            flag = true;
        }
    }

    // 添加消息到聊天窗口
    function addMessage(content, type) {
        const now = new Date();
        const timeStr = now.toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit'
        });
        let $message = "";
        if(flag){
            $message = $(`
            <div class="message ${type}" >
                <div class="message-content" id="${type}">${content}</div>
                <div class="message-time">${timeStr}</div>
            </div>
        `);
        }else{
            let $divContent =  $("div[id='"+type+"']");
            var txt = $divContent.html();
            $divContent.html(txt += content)
        }
        $('.chat-messages').append($message);
        scrollToBottom();
        flag = false;
    }
    // 滚动到底部
    function scrollToBottom() {
        // const container = $('.chat-messages');
        // const threshold = 100; // 距离底部阈值
        // // 如果用户手动滚动了就不自动滚动
        // if(container[0].scrollHeight - container.scrollTop() - container.outerHeight() > threshold) {
        //     return;
        // }
        $('.chat-messages').animate({
            scrollTop: $('.chat-messages')[0].scrollHeight
        }, 10);
    }

    // 事件绑定
    $('#send-btn').click(sendMessage);
    $('#message-input').keypress(function(e) {
        if(e.which === 13 && !e.shiftKey) {
            e.preventDefault();
            sendMessage();
        }
    });

    /**
     * 使用正则表达式去除字符串中包含 多余字符
     */
    function sanitizeString(str) {
        str = str.replace(/data|think|dat|:|<think>|data:|/g, '');
        return str;
    }
});